import { HttpException, Injectable, NotFoundException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { getPagination, mapToObj } from 'src/utils';
import { ILike, Repository } from 'typeorm';
import { EditRoleDto, ListDTO } from './dto/create-role.dto';
import { RolesEntity } from './entity/role.entity';

export interface RolesRo {
  list: RolesEntity[];
  count: number;
}

/**
 * @desc 实现CRUD操作的业务
 */
@Injectable()
export class RoleService {
  constructor(
    @InjectRepository(RolesEntity)
    private readonly rolesRepository: Repository<RolesEntity>,
  ) {}

  // 创建角色
  async create(post: Partial<RolesEntity>): Promise<RolesEntity> {
    const { role_code } = post;
    if (!role_code) {
      throw new HttpException('缺少角色编码', 401);
    }
    const doc = await this.rolesRepository.findOne({ where: { role_code } });
    if (doc) {
      throw new HttpException('角色编码已存在', 401);
    }
    return await this.rolesRepository.save(post);
  }

  // 获取角色列表
  async findAll(query: ListDTO): Promise<any> {
    const { page = 1, pageSize = 10, role_name } = query;
    // 自定义查询条件
    const queryMap = new Map();
    queryMap.set('del_flag', 0);
    if (role_name) {
      queryMap.set('role_name', ILike(role_name));
    }

    const getList = this.rolesRepository
      .createQueryBuilder('sys_roles')
      .where(mapToObj(queryMap))
      .select([
        'sys_roles.id',
        'sys_roles.role_name',
        'sys_roles.description',
        'sys_roles.create_time',
        'sys_roles.update_time',
      ])
      .skip((page - 1) * pageSize)
      .take(pageSize)
      .printSql()
      .getManyAndCount();

    const [list, total] = await getList;
    const pagination = getPagination(total, pageSize, page);
    const result = {
      result: list,
      pagination,
    };

    return result;
  }

  // 通过id获取指定角色信息
  async findById(query) {
    const { id } = query;
    const sql = `SELECT role_name,id,role_code,description,create_time,update_time,create_by FROM sys_roles WHERE id ='${id}' AND del_flag=0`;
    const roleDetial = await this.rolesRepository.query(sql);
    if (roleDetial.length == 0) {
      throw new NotFoundException('找不到对应id数据');
    }
    const result = {
      result: roleDetial[0],
    };
    return result;
  }

  // 更新角色
  async updateById(id: string, body: EditRoleDto) {
    const reslut = await this.rolesRepository.update(id, body);
    return reslut;
  }

  // 删除角色
  async remove(query) {
    const { id } = query;
    const sql = `SELECT role_name,id FROM sys_roles WHERE id ='${id}' AND del_flag=0`;
    const existRole = await this.rolesRepository.query(sql);
    if (existRole.length == 0) {
      throw new HttpException(`id为${id}的角色不存在`, 401);
    }
    const update_sql = `UPDATE sys_roles SET del_flag=1 WHERE id='${id}'`;
    const result = await this.rolesRepository.query(update_sql);
    if (result) {
      return '删除成功！';
    } else {
      return '删除失败！';
    }
  }
}
